import Vue from 'vue';
import Service from './service';

export default class http extends Service {
  constructor() {
    super();
    this.vm = new Vue();
  }

  fetch(type, url, params = {}, config = {}, loading) {
    const awaitTime = new Promise((resolve) => {
      setTimeout(resolve, 1000, 'isShowLoading');
    });

    const fetchData = new Promise((resolve, reject) => {
      this.instance[type](url, params, config)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
        .finally(() => {
          if (loading) {
            this.closeLoading();
          }
        });
    });

    Promise.race([fetchData, awaitTime]).then((data) => {
      if (data === 'isShowLoading') {
        this.showLoading(loading);
      }
    });

    return fetchData;
  }

  get({ url, params = {}, config = { isCheckToken: true } }, loading) {
    return this.fetch('get', url, { params, ...config }, null, loading);
  }

  post({ url, params = {}, config = { isCheckToken: true } }, loading) {
    return this.fetch('post', url, params, config, loading);
  }

  closeLoading() {
    setTimeout(() => {
      this.vm.$toast.clear();
    }, 400);
  }

  showLoading({ text = '加载中...', show = false } = {}) {
    if (show) {
      this.vm.$toast.loading({
        mask: true,
        message: text,
        duration: 0,
      });
    }
  }
}
